package org.asociacion.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import org.asociacion.backend.bo.IndexImageBo;
import org.asociacion.backend.service.IndexService;
import org.asociacion.backend.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("index")
public class LoginController {
	
	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private IndexService indexService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping
	public String index(Model model, HttpServletResponse httpServletResponse){
		Properties properties = indexService.getProperties();
		Properties propertiesText = indexService.getPropertiesText();
		model.addAttribute("properties", properties);
		model.addAttribute("propertiesText", propertiesText);
		model.addAttribute("listSliderName", indexService.getListImageName("slider", false));		
		model.addAttribute("listProject", indexService.getListImageName("project", false));
		return "index";
	}
	
	@RequestMapping(value="image/{folder}/{name}")
	public void downloadFile(@PathVariable("folder") String folder, @PathVariable("name") String name, 
			HttpServletResponse httpServletResponse) {
		IndexImageBo indexImageBo = indexService.getImage(folder, name);
		if (indexImageBo != null) {
			httpServletResponse.setHeader("Content-Disposition", 
					"inline;filename=\"" + indexImageBo.getName() + indexImageBo.getType().toString() + "\"");
			try (OutputStream outputStream = httpServletResponse.getOutputStream()) {
				outputStream.write(indexImageBo.getImage());
				outputStream.flush();
			} catch (IOException ex) {
				log.error("Error loading image", ex);
			}
		} else {
			if (log.isDebugEnabled()) {
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.append("Image not found in folder:").append(folder).append(" and name:").append(name);
				log.debug(stringBuilder.toString());
			}
		}
	}

	public void setIndexService(IndexService indexService) {
		this.indexService = indexService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
